<?php

declare(strict_types=1);

namespace app\admin\command;

use app\common\model\Matches as ModelMatches;
use GuzzleHttp\Promise\Is;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Matches extends Command
{
    //定时器 更新赛事每天的信息  timestamp 为0默认全部 获取当天的数据直接放当日的时间戳时间戳
    //需要实时更新
    protected function configure()
    {
        // 指令配置 php think matches football -t 1
        $this->setName('matches')
            ->addArgument('action', Argument::OPTIONAL, '参数')
            ->addOption('tab', 't', Option::VALUE_OPTIONAL, '区别0 1 2 3 4 5')
            ->setDescription('赛事');
    }
    /**
     * tab 
     * 推荐 5
     * 全部 0 
     * 进行中 1
     * 赛程 2
     * 赛果 3 
     * 关注 4
     * 
     */

    protected function execute(Input $input, Output $output)
    {
        $action = trim($input->getArgument('action'));
        $tab = trim($input->getOption('tab'));
        $data['competition_ids'] = [];
        $data['page'] = 1;
        $data['tab'] = intval($tab);
        $data['timestamp'] = 0; //0 默认全部  获取当天的数据直接放当日的时间戳时间戳
        $url = 'https://api-f.kqiu.cn/api/v1/' . $action . '/matches';
        $limit = 20; //每页显示的数量
        $data['size'] = $limit; //每页显示的数量
        $page = 0;
        do {
            $page++;
            $data['page'] = $page; //当前页码
            $apiData = $this->httpApiUrl($url, $data);
            //入库
            $this->insertLinkMysql($apiData, $action, $output,$tab);
        } while ($page < ceil($apiData['data']['total'] / $limit));
        // 指令输出
        $output->writeln('完成');
    }

    /**
     * curl
     */
    protected function httpApiUrl($url, $postData)
    {
        $res = curl_post($url, json_encode($postData));
        $arr = json_decode($res, true);
        return $arr;
    }

    /**
     * 入库
     */
    public function insertLinkMysql($arr, $action, $output,$tab)
    {
        $output->writeln('=========================开始===============================');
        if (array_key_exists('data', $arr)) {
            if ($arr['code'] == 0 && $arr['data']['total'] > 0) {
                foreach ($arr['data']['results'] as $key => $v) {
                    $output->writeln('=========================循环第' . ($key + 1) . '个数据，开始循环赛事名称为:' . $v['competition_name'] . '=====================================');
                    $v['api_id'] = $v['id'];
                    $v['odds'] = json_encode($v['odds'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    $v['init_odds'] = json_encode($v['init_odds'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    $v['live'] = json_encode($v['live'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    if (!empty($v['pre_odds'])) {
                        $v['pre_odds'] = json_encode($v['pre_odds'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    }
                    if (!empty($v['incidents'])) {
                        $v['incidents'] = json_encode($v['incidents'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    }
                    $v['type'] = $action;
                    $v['type_tab'] = $tab;
                    unset($v['id']);
                    if ($action == 'football') {
                        $is_find = ModelMatches::field('id,home_team_name')->where('match_id', '=', $v['match_id'])->findOrEmpty();
                        $match_id = $v['match_id'];
                    } else {
                        $is_find = ModelMatches::field('id,home_team_name')->where('api_id', '=', $v['api_id'])->findOrEmpty();
                        $match_id = $v['api_id'];
                    }
                    if (!$is_find->isEmpty()) {
                        //更新
                        $is_find->save($v);
                        $str = 'update';
                        $key_id = $is_find->id;
                    } else {
                        $model = ModelMatches::create($v);
                        $key_id = $model->id;
                        $str = 'add';
                    }
                    // //查询详情===>入库
                    $this->matchesDetail($action, $match_id, $key_id, $output);
                    $output->writeln('=========================' . $str . '完成=====================================');
                }
            } else {
                $output->writeln('api参数出错');
            }
        }
        $output->writeln('=========================结束===============================');
    }

    //赛事详情
    public function matchesDetail($action, $match_id, $key_id, $output)
    {
        $output->writeln('=========================详情开始===============================');
        $model = ModelMatches::find($key_id);
        $url = 'https://api-f.kqiu.cn/api/v1/' . $action . '/match/detail?match_id=' . $match_id;
        $res = curl_get($url);
        $arr = (json_decode($res, true));
        if ($arr['code'] == 0) {
            if (!empty($arr['data']['tabs'])) {
                $tabs = json_encode($arr['data']['tabs'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            }
            $model->save(['stage_name' => $arr['data']['stage_name'], 'tabs' => $tabs ?? '']);
            $output->writeln('=========================' . $model['competition_name'] . '更新结束===============================');
        }
        $output->writeln('=========================详情结束===============================');
    }
}
